/***
 * 脚本依赖;
 * common.js
 * ejs.js
 * $,jQuery
 *
 */
(function ($) {
    var $Card = {
        tableSelect: function ($table, destroyBtn, createBtn, options) {
            $table.find('tbody tr').unbind('click').click(function () {
                if ($(this).text() && $(this).text().indexOf('没有找到符合查询条件的数据!') > -1) {
                    searchInputValue('search'); //
                    return;
                }
                if ($(this).hasClass('active')) {
                    destroyBtn && destroyBtn();
                    $(this).removeClass('active').find('td:first-child input[type=checkbox]').attr('checked', false).prop('checked', false);
                } else {
                    if ($(this).data('json')) {
                        createBtn && createBtn(this);
                        var $checkbox = $(this).addClass('active').find('td:first-child input[type=checkbox]');
                        if ($checkbox.length) {
                            $checkbox.attr('checked', true).prop('checked', true);
                            if (!options.multiSelect) { // 单选
                                $checkbox.closest('tr').siblings('tr').removeClass('active').find('td:first-child input[type=checkbox]').attr('checked', false).prop('checked', false);
                            }
                        } else {
                            $(this).addClass('active');
                            if (!options.multiSelect) { // 单选
                                $(this).closest('tr').siblings('tr').removeClass('active').find('td:first-child input[type=checkbox]').attr('checked', false).prop('checked', false);
                            }
                        }
                    }
                }
            })
        },
        'sort': function ($table, search) {
            $table.find('th .fa').unbind('click').click(function (e) {
                var sort = {sortField: '', sortOrder: ''};
                sort.sortField = $(this).data('sort');
                if ($(this).hasClass('fa-sort') || $(this).hasClass('fa-sort-desc')) {
                    sort.sortOrder = 'ASC';
                    $(this)
                        .removeClass('fa-sort-desc fa-sort')
                        .addClass('fa-sort-asc');
                    $(this)
                        .closest('th')
                        .siblings('th')
                        .find('.fa')
                        .removeClass('fa-sort-desc fa-sort-asc')
                        .addClass('fa-sort');
                } else if ($(this).hasClass('fa-sort-asc')) { //asc
                    sort.sortOrder = 'DESC';
                    $(this)
                        .removeClass('fa-sort-asc fa-sort')
                        .addClass('fa-sort-desc');
                    $(this)
                        .closest('th')
                        .siblings('th')
                        .find('.fa')
                        .removeClass('fa-sort-desc fa-sort-asc')
                        .addClass('fa-sort')
                }
                search && search(sort);
            })

        },
        initThead: function () {
            var $tr_ = $('<tr></tr>');
            options.fields.forEach(function (item, index1) {
                if (index1 == 0) {
                    if (options.checkbox || options.radio) {
                        $tr_.append($('<th></th>'));
                    }
                    if (options.seqNum) {
                        $tr_.append($('<th>序号</th>').css({width: 35}));
                    }
                }
                var $th = $('<th>' + item.label + '</th>');
                if (item.enableSort) {
                    $th.append($('<i data-sort="name" class="pull-right fa fa-sort"></i>'));
                }
                $tr_.append($th);
            });

        },
        /***
         * 初始化搜索框
         */
        initSearch: function (options) {
            if ($('input.search').length) {
                return false;
            }
            //basic search
            var $searchType = $('<div class="input-group-btn"></div>'),
                $searchTypeDown = $('<ul class="dropdown-menu" role="menu"></ul>'),
                $searchTypeLabel = $('<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">单位名称 <span class="caret"></span></button>'),
                $searchInput = $('<input type="text" class="form-control search" data-toggle="autocomplete" data-lookup="[&quot;aaa&quot;, &quot;bbb&quot;, &quot;ccc&quot;, &quot;ddd&quot;, &quot;edfa&quot;, &quot;wdasda&quot;, &quot;tueiyhgk&quot;, &quot;vjflcjx&quot;]" placeholder="请输入...">'),
                $searchBtn = $('<span class="input-group-btn"><button class="btn btn-primary search-btn" data-loading-text="查询中..." type="button">查询</button></span>'),
                $searchCtner = $('<div class="input-group pull-left" style="width: 250px;"></div>');
            var $searchSenior = $('<div class="search-senior"></div>'),
                $searchFormInline = $('<div class="form-inline"></div>'),
                length = 0;
            options.fields.forEach(function (item, index) {
                if (item.enableSearch) {
                    length++;
                    var $item = $('<li><a href="#">' + item.label + '</a></li>');
                    var $seniorItem = '';
                    if (item.dateRange) { //日期范围搜索
                        $seniorItem = $('<div class="form-group input-daterange" data-toggle="datepicker" data-date-start-date="' + (item.start || '2017-03-01') + '"' +
                            ' data-date-end-date="' + ((item.end || moment(Date.now()).format('YYYY-MM-DD'))) + '"><label class="sr-only">' + item.label + ':</label>' +
                            '<input type="text" name="' + item.name + 'Start" data-date-size="small" readonly="readonly" class="form-control input-date"' +
                            ' placeholder="' + item.label + '开始日期"' +
                            ' style="width: 125px;">-<input  name="' + item.name + 'End"  readonly="readonly"  data-date-size="small" type="text" class="form-control input-date" ' +
                            ' style="width: 125px;" placeholder="' + item.label + '结束日期" >');
                    } else {
                        $seniorItem = $('<div class="form-group"><label class="sr-only"></label>' +
                            '<input type="text" class="form-control" name="' + item.name + '" placeholder="' + item.label + '">&nbsp;</div>');
                        $seniorItem = $('<div class="form-group ><label class="sr-only"></label>' +
                            '<input type="text" class="form-control" name="' + item.name + '" placeholder="' + item.label + '">&nbsp;</div>');
                    }
                    $item.data('json', item);
                    $searchTypeDown.append($item);
                    $searchFormInline.append($seniorItem.css({margin: '0 5px 11px 0'}));
                    $item.unbind('click').click(function () {
                        var $data = $(this).data('json');
                        $searchTypeLabel.html($data.label + ' <span class="caret"></span>').data('json', $data);
                    });
                    if (!$searchTypeLabel.data('json')) { // 未初始化
                        $searchTypeLabel.html(item.label + ' <span class="caret"></span>').data('json', item)
                    }
                }
                if (item.enableFilter) {
                    length++;
                    var $item = $('<li><a href="#">' + item.label + '</a></li>');
                    var $seniorItem = $('<div class="form-group"><label class="sr-only">' + item.label + '：</label>' +
                        '<select type="text" class="form-control" name="' + item.name + '" placeholder="' + item.label + '">' +
                        item.filters.map(function (item) {
                            return '<option value="' + item.value + '">' + item.label + '</option>';
                        }).join('') +
                        '</select></div>');

                    $item.data('json', item);
                    $searchTypeDown.append($item);
                    $searchFormInline.append($seniorItem.css({margin: '0 5px 11px 0'}));
                }
            });
            if (length == 0)return;
            $searchType.append($searchTypeLabel).append($searchTypeDown);
            if (options.complexItems && options.showSearchComplex) {
                options.complexItems.forEach(function (item) {
                    var $seniorItem = '';
                    if (item.dateRange) { //日期范围搜索
                        $seniorItem = $('<div class="form-group input-daterange" data-toggle="datepicker" data-date-start-date="' + (item.start || '2017-03-01') + '"' +
                            ' data-date-end-date="' + ((item.end || moment(Date.now()).format('YYYY-MM-DD'))) + '"><label class="sr-only">' + item.label + ':</label>' +
                            '<input type="text" name="' + item.name + 'Start" data-date-size="small" class="form-control input-date"' +
                            ' placeholder="' + item.label + '开始日期"' +
                            ' style="width: 125px;">-<input  name="' + item.name + 'End"  data-date-size="small" type="text" class="form-control input-date" ' +
                            ' style="width: 125px;" placeholder="' + item.label + '结束日期" />&nbsp;');
                    } else {
                        $seniorItem = $('<div class="form-group"><label class="sr-only">' + item.label + '：</label>' +
                            '<input type="text" class="form-control" name="' + item.name + '" placeholder="' + item.label + '">&nbsp;</div>');
                        $seniorItem = $('<div class="form-group ><label class="sr-only">' + item.label + '：</label>' +
                            '<input type="text" class="form-control" name="' + item.name + '" placeholder="' + item.label + '">&nbsp;</div>');
                    }
                    $searchFormInline.append($seniorItem.css({marginBottom: '10px'}));
                })
            }
            $searchBtn.unbind('click').click(function () { // 单项搜索
                var $data = $searchTypeLabel.data('json');
                var obj = {};
                var $lis = $(this).closest('.input-group').find('li');
                $lis.each(function () {
                    var $json = $(this).data('json');
                    obj[$json.name] = ""; // 单项搜索时，过滤非当前项条件干扰
                });
                obj[$data.name] = $searchInput.val();
                obj.page = 1;
                options.search && options.search(obj)
            });

            $searchCtner.append($searchType).append($searchInput).append($searchBtn);

            var $searchSwitch = $('<a class="search-switch pull-left">高级搜索</a>'),
                $search = $('<button type="submit" class="btn btn-primary">搜索</button>'),
                $export = $('<button type="submit" class="btn btn-primary export">导出</button>');
            $searchFormInline.append($search.css({margin: '0 5px 11px 0'}));
            $search.unbind('click').click(function () { // 高级搜索
                var search = {};
                $(this).siblings('.form-group').find('input,select').each(function (index, item) {
                    search[item.name] = item.value;
                });
                options.search && options.search(search)
            });
            $searchSenior.hide();
            $searchSenior.append($searchFormInline);
            $searchSwitch.unbind('click').click(function () {
                if ($(this).text().indexOf('高级') > -1) {
                    $(this).text('普通搜索');
                    $searchCtner.hide();
                    $searchSenior.show();
                    $searchSenior.find('input[name=' + $searchTypeLabel.data('json')['name'] + ']').val($searchInput.val())
                } else {
                    $searchCtner.show();
                    $searchSenior.hide();
                    $searchInput.val($searchSenior.find('input[name=' + $searchTypeLabel.data('json')['name'] + ']').val());
                    // $searchSenior.find('input[name='+$searchTypeLabel.data('json')['name']+']').val($searchInput.val())
                    $(this).text('高级搜索')
                }
            });

            $searchSenior.css({padding: '12px 12px 0'});
            $searchFormInline.css({paddingBottom: '0px'});
            $(options.toolbar).find('.pull-right').append($searchCtner);
            if (length > 1 || options.showSearchComplex) {
                $(options.toolbar).find('.pull-right').append($searchSwitch);
                if (options.showSearchComplex) {
                    $searchSwitch.click().hide();
                }
            }
            if (options.export) {
                var date = new Date();
                $searchFormInline.find('[name=dateStart]').val(getMonthBeginAndEnd().start);
                $searchFormInline.find('[name=dateEnd]').val(getMonthBeginAndEnd().end);
                $export.unbind('click').click(function () {
                    if (options.search) {
                        var search = {};
                        $(this).siblings('.form-group').find('input,select').each(function (index, item) {
                            search[item.name] = item.value;
                        });
                        generateExportUrl(options.search({}, true, true));
                    }
                });
                $searchFormInline.append($export.css({margin: '0 5px 11px 0'}));
            }
            $searchFormInline.find('input[type=text]').unbind('keydown').keydown(function (e) { // 高级搜索
                if (e.keyCode == 13) {
                    $search.click();
                }
            });
            $searchCtner.find('input[type=text]').unbind('keydown').keydown(function (e) { // 高级搜索
                if (e.keyCode == 13) {
                    $searchBtn.click();
                }
            });
            $searchSenior.insertBefore($(options.toolbar).closest('.panel-body'));
        },
        initTbody: function (options) {

        },
        initCellData: function (item, rowData, index1, dataArray, options) {
            return (!!item.filter ? item.filter(rowData, dataArray) : ((rowData[options.fields[index1].name] != 0) ? (rowData[options.fields[index1].name] || '-') : rowData[options.fields[index1].name]))
        },
        initCustomColumn: function (options) {
            if ($('[multiple="multiple"]').length)return;
            if (options.fields.length < 5)return;
            var $multiEle = $('<select data-placeholder="自定义列" multiple="multiple"></select>');
            $(options.toolbar).find('.pull-right').append($multiEle);
            var $multi = $multiEle.multiselect($.extend(MULTI_SETTING, {
                onDropdownHide: function (event) {
                    // console.log($multi.multiselect('getSelected'))
                },
                onChange: function (option, selected) {
                    if (!selected) {
                        $('.custom-' + $(option).val()).hide()
                    } else {
                        $('.custom-' + $(option).val()).show()
                    }
                    // console.log($multiEle.val());
                    $.post('/user/setting', {
                        module: window.location.pathname,
                        columns: $multiEle.val().join(',')
                    })
                },
                // onDeselectAll: function() {
                //     alert('onDeselectAll triggered!');
                // }
            }));
            $.post('/user/getSetting', {
                module: window.location.pathname,
            }, function (item_) {
                if (!item_.data) {
                    var options_ = options.fields.map(function (item) {
                        item.value = item.name;
                        item.selected = true;
                        return item;
                    });
                    $multi.multiselect('dataprovider', options_);
                } else {
                    var options_ = options.fields.map(function (item) {
                        item.value = item.name;
                        if (item_.data.columns) {
                            // item_.data.columns = item_.data.columns;
                            if (item_.data.columns.indexOf(item.name) > -1) {
                                item.selected = true;
                                $('.custom-' + item.name).show()

                            } else {
                                item.selected = false;
                                $('.custom-' + item.name).hide()
                            }
                        } else {
                            item.selected = false;
                        }
                        return item;
                    });
                    $multi.multiselect('dataprovider', options_);
                }
            });
        },
        initRowHead: function (options, $tr, length, index) {
            if (options.checkbox) {
                $tr.append($('<td class="vm" rowspan="' + length + '" ><input type="checkbox"/></th>'));
            }
            if (options.radio) {
                $tr.append($('<td class="vm" rowspan="' + length + '"><input type="radio" name="radio"/></th>'));
            }
            if (options.seqNum) {
                $tr.append($('<td class="vm" rowspan="' + length + '">' + (index + 1) + '</th>'));
            }
            return $tr;
        },
        init: function (options) {
            var $table = $(this);
            //initSubPageScroll();
            // if (options.data.length == 0) {
            //     $table.find('tbody').html(noData());
            // }
            var $trTotal_ = $('<tr></tr>'), total_ = {};
            options.data.forEach(function (obj, index) {
                var $item = $('<div>' +
                    '<div class="list-item-image "><a ' + ((options.isLeaf && obj.type1 == 0) ? ('style="margin:0;"') : '') + ' href="' + (options.isLeaf ? 'javascript:void(0);' : './folder.html?id=' + obj.id + '&name=' + obj.name + '&remark=' + obj.remark) + '" class="image-container">' +
                    (options.isLeaf ? (obj.type1 == 0 ? '<img src="' + obj.url + '" alt="' + obj.name + '" width="430" height="430" class="jsly jsly-loaded" style="display: block; width: 159px; height: 159px;">' : '<i class="icon icon-file-text2 empty"></i>') : '<i class="icon icon-folder-open empty"></i>') +
                    '</a>' +
                    '<ul class="list-item-image-tools" data-action="list-tools"> \
                    <li  class="tool-select" data-action="select"> \
                    <a  href="' + (options.isLeaf ? 'javascript:void(0);' : './folder.html?id=' + obj.id + '&name=' + obj.name + '&remark=' + obj.remark) + '" data-icon-selected="icon-ok" data-icon-unselected="icon-checkbox-unchecked" class="btn-icon icon-checkbox-unchecked" title="选择"></a> \
                    <span class="label label-select">选择</span> \
                    </li> \
                    ' + (options.isLeaf ? '' : '<li class="tool-edit" data-action="edit"><span class="btn-icon icon-pencil2"></span><span class="label label-edit">编辑</span></li>') + ' \
                    <li class="tool-delete" data-action="delete"> \
                    <a href="javascript:void(0);" class="btn-icon icon-bin2" title="删除"></a> \
                    <span class="label label-remove">删除</span> \
                    </li> \
                    </ul>' +
                    '</div>' +
                    (options.isLeaf ? '' : '<div class="list-item-thumbs-container"> \
                    <ul class="list-item-thumbs"> \
                    <li  style="width: 25%; height: 35px;"></li> \
                    <li  style="width: 25%; height: 35px;"></li> \
                    <li  style="width: 25%; height: 35px;"></li> \
                    <li  style="width: 25%; height: 35px;"></li> \
                    </ul> \
                    </div>') +
                    '<div class="list-item-desc"> \
                    <div class="list-item-desc-title"> \
                    <a class="list-item-desc-title-link" href="javascript:void(0)">' + obj.name + '</a>\
                    ' + (!options.isLeaf ? '<span class="display-block font-size-small"></span>' : '') + ' \
                </div> \
                <div class="list-item-like" data-action="like"> \
                    <span class="btn-like btn-liked icon-heart3"></span> \
                    <span class="btn-like btn-unliked icon-heart4"></span> \
                    </div> \
                    </div> \
                    </div>'
                )
                $item.addClass('card-item gutter-margin-right-bottom ');
                $item.data(obj)
                $item.insertBefore($table.find('.hp-clearfix'));
            });

            onClick($('.tool-select'), function () {
                var $JSON = $(this).closest('.card-item').data();
                var $index = dialogForm(
                    {
                        noForm: true,
                        width: ['600px', '230px'],
                        title: "'" + $JSON.name + "'嵌入代码",
                        data: [

                            {
                                type: 'text',
                                label: '图片URL链接',
                                placeholder: '图片URL链接',
                                val: $JSON.url || '',
                                name: 'desc1'
                            },
                            {
                                type: 'text',
                                label: '完整图片',
                                placeholder: '完整图片',
                                val: $JSON.url ? '<img src="' + ($JSON.url) + '" alt="' + $JSON.name + '" border="0" />' : '',
                                name: 'html'
                            },
                            {
                                type: 'text',
                                label: '完整图片（链接）',
                                placeholder: '完整图片（链接）',
                                val: $JSON.url ? '<a href="'+$JSON.url+'" ><img src="' + ($JSON.url) + '" alt="' + $JSON.name + '" border="0" /></a>' : '',
                                name: 'html'
                            },
                        ],
                    });
            })
            onClick($('.tool-edit'), function () {
                var $JSON = $(this).closest('.card-item').data();
                var $index = dialogForm(
                    {
                        title: "编辑",
                        data: [
                            {
                                type: 'text',
                                label: '文件夹名称',
                                require: true, // 是否必填
                                placeholder: '请输入文件夹名称',
                                val: $JSON.name || '',
                                name: 'name'
                            },
                            {
                                type: 'text',
                                label: '文件夹描述',
                                placeholder: '请输入文件夹描述',
                                val: $JSON.desc1 || '',
                                name: 'desc1'
                            },
                        ],
                        submit: function (form) {
                            form.id = $JSON.id;
                            form.type1 = 'folder'; // 数据类型菜单
                            $.post('/category/update', form, function (res) {
                                if (res.code == 200) {
                                    fnSuccess("操作成功");
                                    //search({}, true);
                                    closeLayer($index);
                                } else {
                                    fnFail("操作失败");
                                }
                            })
                        }
                    });
            })
            onClick($('.tool-delete'), function () {
                var form = {};
                if (confirm('确认删除?')) {
                    var $JSON = $(this).closest('.card-item').data();
                    form.id = $JSON.id;
                    form.type1 = 'folder'; // 数据类型菜单
                    $.post(options.delUrl || '/category/delete/' + $JSON.id, form, function (res) {
                        if (res.code == 200) {
                            fnSuccess("操作成功");
                            options.search && options.search({}, true);
                            $(this).closest('.card-item').remove();
                        } else {
                            fnFail("操作失败");
                        }
                    })
                }
            })
            if (options.rendered) {
                options.rendered && options.rendered();
            }
        },
        show: function () {
            // is
        },
        hide: function () {
            // good
        },
        update: function (content) {
            // !!!
        }
    };
    $.fn.$card = function (options) {
        var _default = {
            fields: []
        };
        options = $.extend({}, _default, options || {});
        if (!$.isArray(options.fields) || !options.fields.length) {
            throw new Error('option.field must be array and option.field.length must over 0 !')
        }
        return this.each(function () {
            $Card.init.call(this, options);
        })
    };
})(jQuery);


